package arithmetic.sort;

/**
 * 归并排序 看不懂了！！！
 * <p>
 * </p>
 * DATE 2020/4/14.
 *
 * @author cuihao.
 */
public class MergeSort {

    public static void mergeSort(int[] arr, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            mergeSort(arr, low, mid);
            mergeSort(arr, mid + 1, high);
            merge(arr, low, mid, high);
        }
    }

    public static void merge(int[] arr, int low, int mid, int high) {
        int[] temp = new int[(high - low) + 1];
        int left = low;
        int right = mid + 1;
        int i = 0;
        while (left <= mid && right <= high) {
            if (arr[left] < arr[right]) {
                temp[i++] = arr[left++];
            } else {
                temp[i++] = arr[right++];
            }
        }
        while (left <= mid) {
            temp[i++] = arr[left++];
        }
        while (right <= high) {
            temp[i++] = arr[right++];
        }
        for (int j = 0; j < temp.length; j++) {
            arr[low + j] = temp[j];
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5, 12, 57, 2, 6,};
        mergeSort(arr, 0, arr.length - 1);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
